package com.hontech.bvapp2.ui

import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Bitmap
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.hontech.bvapp2.utils.await
import com.hontech.bvapp2.utils.hideSoftKey
import com.hontech.bvapp2.utils.runNewThread
import kotlinx.coroutines.CompletableDeferred
import java.io.ByteArrayOutputStream

open class BaseActivity : AppCompatActivity() {

    companion object {
        lateinit var INSTANCE: BaseActivity
            private set

        fun parentView(): View {
            return INSTANCE.window.decorView
        }
    }

    private var permissionFuture: CompletableDeferred<Boolean>? = null

    private var actionDownTimestamp = 0L

    @SuppressLint("MissingSuperCall")
    override fun onConfigurationChanged(newConfig: Configuration) {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        INSTANCE = this
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            hideSoftKey(this)
            actionDownTimestamp = System.currentTimeMillis()
        } else if (ev.action == MotionEvent.ACTION_UP) {
            val current = System.currentTimeMillis()
            if ((current - actionDownTimestamp) > 2000) {
                actionDownTimestamp = current
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    fun hideButton() {
        val decorView = window.decorView
        val uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                View.SYSTEM_UI_FLAG_FULLSCREEN
        decorView.systemUiVisibility = uiOptions
    }

    suspend fun requestPermission(permission: String) {
        if (PackageManager.PERMISSION_GRANTED == checkSelfPermission(permission)) {
            return
        }
        val fut = CompletableDeferred<Boolean>()
        permissionFuture = fut
        requestPermissions(arrayOf(permission), 0)
        val ret = fut.await(30 * 1000, "请授权:$permission")
        if (!ret) {
            throw IllegalStateException("没有授权 $permission")
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty()) {
            permissionFuture?.complete(grantResults[0] == PackageManager.PERMISSION_GRANTED)
        }
    }

    suspend fun screenShot(): ByteArray {
        val view = window.decorView
        view.isDrawingCacheEnabled = true
        val bitmap = Bitmap.createBitmap(view.drawingCache)
        view.isDrawingCacheEnabled = false

        return runNewThread {
            val output = ByteArrayOutputStream()
            output.use {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
                output.flush()
            }
            output.toByteArray()
        }
    }

}

